<template>
  <div class="container">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="ruleForm" status-icon>
      
      <div class="form-section">
        <div class="flag"></div>
        <span class="title">基本信息</span>
        <el-divider></el-divider>
      </div>

      <el-form-item label="分组名称" prop="name">
        <el-input v-model.trim="ruleForm.name" maxlength="32" :disabled="is_preview" show-word-limit placeholder="请输入分组名称" style="width:500px;"></el-input>
      </el-form-item>

      <el-form-item label="分组备注">
        <el-input type="textarea" v-model.trim="ruleForm.note" :disabled="is_preview" maxlength="255" show-word-limit placeholder="请输入分组备注" style="width:500px;"></el-input>
      </el-form-item>

      <div class="form-section">
        <div class="flag"></div>
        <span class="title">分组规则</span>
        <el-divider></el-divider>
      </div>

      <el-form-item label="上传用户信息">
        <el-button type="success" :disabled="upload || is_preview" @click="handleImport" plain>选择文件</el-button>
        <div v-if="!validate && ruleForm.userNum === 0" class="cus-form-item__error">请上传用户信息</div>
      </el-form-item>

      <el-form-item label="更新方式">
        <span>手动更新</span>
        <span style="color:#E6A23C;font-size: 12px;">（仅支持手动上传文档进行更新）</span>
      </el-form-item>

      <el-form-item label="用户数量">
        <span>{{ ruleForm.userNum }} 人</span>
        <span v-if="this.pageType === 'edit' && ruleForm.userNum != initialNumber" style="color:#E6A23C;font-size: 12px;">（用户未去重，保存后查看实际人数）</span>
      </el-form-item>

      <el-form-item label="是否启用">
        <el-radio-group v-model="ruleForm.enable" @change="handleEnable" :disabled="is_preview">
          <el-radio label="open">启用</el-radio>
          <el-radio label="close">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item v-if="!is_preview" style="margin-left:100px;">
        <el-button @click="resetForm('ruleForm')" style="margin-right:100px;">取消</el-button>
        <el-button type="success" @click="submitForm('ruleForm')">确定</el-button>
      </el-form-item>
    </el-form>
    
    <!-- upload file dialog -->
    <file-dialog :dialogProp.sync="dialog" @updateUsers="updateUsers"></file-dialog>

  </div>
</template>

<script>
import { checkGroupName, appendUserGroup, editUserGroup, userGroupDetails } from '@/api/userGroup'
import fileDialog from '@/components/userGroup/importCreateGroup/modules/fileDialog'
import { clearTagMixins } from "@/mixins/clearTag.js"

export default {
  msg: '导入创建分组',
  mixins:[clearTagMixins],

  data() {
    // 分组名称空、不可重复校验
    let nameValidate = (rule, value, callback) => {
      if (this.ruleForm.name === '') {
        callback(new Error('请填写分组名称'))
      } else {
        if(this.pageType === 'edit') {
          if(this.ruleForm.name !== this.nameCache){
            checkGroupName({name: value}, (res) => {
              if(res) {
                callback(new Error('分组名称不可重复'))
              } else {
                callback()
              }
            })
          } else {
            callback()
          }
          
        } else {
          checkGroupName({name: value}, (res) => {
            if(res) {
              callback(new Error('分组名称不可重复'))
            } else {
              callback()
            }
          })
        }
      }
    }

    return {
      ruleForm: {
        name: '',
        note: '',
        userNum: 0,
        serial: '',
        enable: 'open'
      },

      // 初始数量
      initialNumber: 0,

      // group name
      nameCache: '',

      rules: {
        name: [
          { required: true, validator: nameValidate, trigger: 'blur' }
        ]
        // note: [
        //   { required: true, message: '请填写分组备注', trigger: 'blur' }
        // ]
      },

      dialog: { visible: false },

      // form validate
      validate: true,

      // enable status
      upload: false
    }
  },

  computed: {
    pageType() {
      // edit / add / preview
      return this.$route.query.pageType
    },

    is_preview() {
      return this.pageType === 'preview' ? true : false
    }
  },

  created() {
    const query = ['preview', 'edit']
    if(query.includes(this.pageType)) {
      userGroupDetails(this.$route.query.id, res => {
        //edit 情况下 【记录下分组名】
        this.nameCache = res.name
        this.initForm(res)
      }, err => {
        this.$message({
          message: err.message,
          type: 'warning'
        })
      })
    }
  },

  methods: {

    // init form
    initForm(data) {
      const { name, note, groupStatus, totalNumber } = data
      
      this.ruleForm.name = name
      this.ruleForm.note = note
      this.ruleForm.userNum = parseInt(totalNumber)
      this.ruleForm.enable = groupStatus ? 'open': 'close'
      this.upload = groupStatus ? false : true
      this.initialNumber = parseInt(totalNumber)
    },

    // submit data
    submitForm(formName) {

      this.validate = true

      this.$refs[formName].validate((valid) => {
        if (!valid) { this.validate = false }

        // validate enable
        if(!this.upload && this.ruleForm.userNum === 0) {
          this.validate = false
        }

        if(this.validate) {

          let { name, note, serial, enable } = this.ruleForm

          const params = {
            name: name,
            note: note,
            updateMethod: 'MANUAL',
            groupCreationType: 'DP',
            serial: serial,
            groupStatus: enable === 'open' ? true: false
          }

          // add
          this.pageType === 'add' && appendUserGroup(params,(res) => {
            this.clearTag()
          },(err) => {
            this.$message({
              message: err.message,
              type: 'warning'
            })
          })

          // edit
          this.pageType === 'edit' && editUserGroup(this.$route.query.id , params ,(res) => {
            this.clearTag()
          },(err) => {
            this.$message({
              message: err.message,
              type: 'warning'
            })
          })
        }
      })
    },

    // update user
    updateUsers(res) {
      this.ruleForm.userNum += parseInt(res.successnum || 0)

      if(res.serial) {
        this.ruleForm.serial = res.serial
      }
    },

    // control upload button
    handleEnable(val) {
      this.upload = val === 'open' ? false : true
    },

    // import file
    handleImport() {
      this.validate = true
      this.dialog.visible = true
    },

    // reset and return last page
    resetForm(formName) {
      this.clearTag()
      // this.$refs[formName].resetFields()
    },

    // close tag
    signOut() {
      this.$router.go(-1)
    }
  },

  components: {
    fileDialog
  }
}
</script>

<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  padding: 20px 50px;
  position: relative;
}

.container .cus-form-item__error {
  font-size: 12px;
  color: #F56C6C;
}

.form-section {
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;

  & .flag {
    width: 5px;
    height: 18px;
    margin-right: 5px;
    background: #1dc8a4;
  }

  & .title {
    width: 100px;
    font-size: 18px;
    font-weight: 600;
    color: #000000;
  }
}

</style>
